<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "user_friend_request".
 *
 * @property int $id ID
 * @property int $user 发起用户
 * @property int $to_user 目标用户
 * @property string $msg 好友申请原因
 * @property int $deal 0未处理，1已接受，2已拒绝
 * @property int $dealtime 接受时间
 * @property int $addtime 添加时间
 */
class UserFriendRequest extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_friend_request';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user', 'to_user', 'addtime'], 'required'],
            [['user', 'to_user', 'dealtime', 'addtime'], 'integer'],
            [['msg'], 'string', 'max' => 150],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user' => '发起用户',
            'to_user' => '目标用户',
            'msg' => '好友申请原因',
            'deal' => '0未处理，1已接受，2已拒绝',
            'dealtime' => '接受时间',
            'addtime' => '添加时间',
        ];
    }
    
    /***
     * 获取用户的好友请求消息列表信息
     */
    public static function getUserRequestMsgNum($userid){
        $sql = "select count(id) nums from user_friend_request where to_user=$userid and deal=0 ";
        $command = \Yii::$app->db->createCommand($sql);
        $data = $command->queryOne();
        return $data['nums'];
    }
    
    /***
     * 获取用户的好友请求消息列表信息
     */
    public static function getUserRequestMsg($userid){
        $sql = "select * from user_friend_request where to_user=$userid and deal=0 ";
        $command = \Yii::$app->db->createCommand($sql);
        $data = $command->queryAll();
        foreach($data as $key => $msg){
            $user = User::findOne(['id'=>$msg['user']]);
            $data[$key]['headimg'] = ($user->headimg === '') ? '/img/user/default-head.png' : $user->headimg;
            $data[$key]['username'] = $user->username;
            $data[$key]['addtime'] = Tools::calculateTimelong($msg['addtime']);
        }
        return $data;
    }
}
